package com.uchengwang.ui.cm_ui.ucity.ui;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.SwitchCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.uchengwang.R;
import com.uchengwang.functions.db.manager.LiteOrmDBUtil;
import com.uchengwang.functions.http.config.BaseConfig;
import com.uchengwang.functions.http.entity.MapRequest;
import com.uchengwang.functions.http.listener.OnResultListener;
import com.uchengwang.functions.http.manager.OSSManager;
import com.uchengwang.ui.UChengApplication;
import com.uchengwang.ui.base_ui.ActivityTitleBar;
import com.uchengwang.ui.base_ui.ui.AllBaseActivity;
import com.uchengwang.ui.cm_ui.cycle.bean.CycleBean;
import com.uchengwang.ui.cm_ui.cycle.bean.CycleShareBean;
import com.uchengwang.ui.cm_ui.cycle.http.CycleHttpUtils;
import com.uchengwang.ui.cm_ui.release.adapter.ThumbtackTileAdapter;
import com.uchengwang.ui.cm_ui.release.bean.SimpleDragEntity;
import com.uchengwang.ui.cm_ui.release.utils.FastReleaseUtils;
import com.uchengwang.ui.cm_ui.release.view.TileView;
import com.uchengwang.ui.cm_ui.ucity.listener.RxBusResultSubscriber;
import com.uchengwang.ui.self.flowLayout.TagAdapter;
import com.uchengwang.ui.self.flowLayout.TagFlowLayout;
import com.uchengwang.ui.utils.ImageManagerUtils;
import com.uchengwang.ui.utils.LoadingUtils;
import com.uchengwang.ui.utils.UCommonUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import cc.solart.dragdrop.DragDropListView;
import cc.solart.dragdrop.IDragEntity;
import cc.solart.dragdrop.adapter.AbsTileAdapter;
import cn.finalteam.rxgalleryfinal.bean.MediaBean;
import cn.finalteam.rxgalleryfinal.rxbus.event.ImageMultipleResultEvent;


/**
 * Created by U城网 on 2018/2/1.
 * 发布享说
 */

public class ReleaseDynamicActivity extends AllBaseActivity implements View.OnClickListener, AbsTileAdapter.DragDropListener{
    private ActivityTitleBar titleBar;
    private EditText dynamic_edit;
    private DragDropListView mListView;
    private LinearLayout dynamic_add;
    private TagFlowLayout dynamic_tag;

    private List<CycleBean> cycleBeanList;
    private TagAdapter tagAdapter;
    private int MAX_IMAGES = 9, chooseImages;
    private ArrayList<MediaBean> mediaBeens = new ArrayList<>();//上个界面传过来的多张图片地址
    private ThumbtackTileAdapter tileAdapter;
    private List<String> paths = new ArrayList<>();
    private ImageView tile_drag_shadow_overlay;

    private RelativeLayout dynamic_switchRl;//同步到校帮圈时
    private SwitchCompat dynamic_switch;
    private RelativeLayout dynamic_add_rl;//同步社圈的布局

    private String ossCover, ossResult;//上传到oss的返回地址
    private CycleBean selectCycleBean;//选中的社圈的标签对象
    private String editString;
    private boolean isAllow = true;

    private int imgsHeight, imgsWidth;//单张图片时上传宽高
    private long cycleId;//社圈id
    private String cycleName;//社圈名称

    //点击图片右上角删除图片的时间
    private ThumbtackTileAdapter.OnDelItemImageListener onDelItemImageListener = new ThumbtackTileAdapter.OnDelItemImageListener() {
        @Override
        public void onDelItemImage(View view, String imageUrl) {
            if (mediaBeens == null || mediaBeens.size()<0)
                return;
            for (int i=0; i<chooseImages; i++){
                if (imageUrl.equals (mediaBeens.get(i).getThumbnailBigPath()) || imageUrl.equals (mediaBeens.get(i).getOriginalPath())){
                    mediaBeens.remove(i);
                    break;
                }
            }
            tileAdapter.setData(obtainData());
            initAddImage();
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_release_dynamic);
        cycleId = getIntent().getLongExtra(BaseConfig.ID, 0);
        cycleName = getIntent().getStringExtra(BaseConfig.PUB_TITLE);

        Log.d("jjf", "社圈id="+cycleId+"==社圈名=="+cycleName);

        initView();
    }

    private void initView(){
        titleBar = (ActivityTitleBar) findViewById(R.id.dynamic_titleBa);
        titleBar.setLeftListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                save();
            }
        });
        titleBar.setRightText("发布", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                editString = dynamic_edit.getText().toString();
                if (TextUtils.isEmpty(editString) && (paths ==null || paths.size() <=0)){
                    UCommonUtil.getUtil().showToast(ReleaseDynamicActivity.this, "请输入上传内容");
                    return;
                }
                if (!isAllow){
                    UCommonUtil.getUtil().showToast(ReleaseDynamicActivity.this, "正在提交...");
                    return;
                }
                isAllow = false;
                releaseImg();

            }
        });
        dynamic_edit = (EditText) findViewById(R.id.dynamic_edit);
        mListView = (DragDropListView) findViewById(R.id.list_view);
//        dynamic_tag = (TagFlowLayout) findViewById(R.id.dynamic_tag);
//        dynamic_switchRl = (RelativeLayout) findViewById(R.id.dynamic_switchRl);
//        dynamic_add = (LinearLayout) findViewById(R.id.dynamic_add);
//        dynamic_add.setOnClickListener(this);
        tile_drag_shadow_overlay = (ImageView) findViewById(R.id.tile_drag_shadow_overlay);

//        dynamic_switchRl = (RelativeLayout) findViewById(R.id.dynamic_switchRl);
        dynamic_switch = (SwitchCompat) findViewById(R.id.dynamic_switch);
//
//        switch (shareType){//图文1   活动2   约玩3  帮问4
//            case 1://享说
//
//                break;
//
//            case 2://活动
//
//                break;
//
//            case 4://帮问
//                dynamic_switchRl.setVisibility(View.GONE);
//                dynamic_switchRl.setVisibility(View.VISIBLE);
//                dynamic_tag.setVisibility(View.GONE);
//                break;
//
//        }
        initImage();
        initSaveData();

//        getMyFollowCycles();
    }

    /**
     * 先查询之前有没有保存的数据
     * */
    private void initSaveData(){
        CycleShareBean cycleShareBean = getSave();
        if (cycleShareBean !=null){
            String s = cycleShareBean.getShareContent();
            dynamic_edit.setText(cycleShareBean.getShareContent());
            String imageAll = cycleShareBean.getShareImg();
            if (!TextUtils.isEmpty(imageAll)){
                List<String> stringList = Arrays.asList(imageAll.split(";"));
                for (int i=0; i <stringList.size(); i++){
                    MediaBean bean = new MediaBean();
                    bean.setThumbnailBigPath(stringList.get(i));
                    mediaBeens.add(bean);
                }
                tileAdapter.setData(obtainData());
            }

        }
    }

    /**
     * 初始化图片
     * */
    private void initImage(){
        tileAdapter = FastReleaseUtils.getUtils().createDragDrop(this, mListView, obtainData(), tile_drag_shadow_overlay, MAX_IMAGES, this, new TileView.OnSelectedListener() {
            @Override
            public void onTileSelected(IDragEntity entity) {
                //点击某个数据的监听器
                if (paths != null && paths.size() >0){
                    UCommonUtil.getUtil().startImagePagerActivity(ReleaseDynamicActivity.this, paths, ((SimpleDragEntity)entity).getId(), true);
                }
            }
        });
        tileAdapter.setOnDelItemImageListener(onDelItemImageListener);
        tileAdapter.setSelectedImages(mediaBeens);

        initAddImage();
    }

    /**
     * 初始化tag
     * */
//    private void initTag(List<CycleBean> cList){
//        final LayoutInflater mInflater = LayoutInflater.from(ReleaseDynamicActivity.this);
//        cycleBeanList = cList;
//
//        tagAdapter = new TagAdapter<CycleBean>(cycleBeanList) {
//            @Override
//            public View getView(FlowLayout parent, int position, CycleBean bean) {
//                TextView tv = (TextView) mInflater.inflate(R.layout.item_flow_view, dynamic_tag, false);
//                tv.setText(bean.getCycleName());
//                return tv;
//            }
//        };
//
//        dynamic_tag.setAdapter(tagAdapter);
//        dynamic_tag.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
//            @Override
//            public boolean onTagClick(View view, int position, FlowLayout parent) {
//                if (selectCycleBean == null){
//                    selectCycleBean = cycleBeanList.get(position);
//                }else {
//                    selectCycleBean = null;
//                }
//                return false;
//            }
//        });
//    }

    private void initAddImage(){
        //选择图片的回调
        if (chooseImages < MAX_IMAGES){
            //已选择的图片 小于最大选择限制
            tileAdapter.setRxSubscriber(new RxBusResultSubscriber<ImageMultipleResultEvent>() {
                @Override
                public void onEvent(ImageMultipleResultEvent event)   {
                    //选择图片点击确定完成时的操作
                    int num = 0;
                    if (event.getResult() != null){
                        num = event.getResult().size();

                        if (num > 0){
                            if (mediaBeens != null){
                                mediaBeens.clear();
                            }
                            mediaBeens = (ArrayList<MediaBean>) event.getResult();
                            //选择图片的总张数
                            chooseImages = mediaBeens.size();
                            if (tileAdapter != null){
                                tileAdapter.setData(obtainData());
                            }
                            tileAdapter.setSelectedImages(mediaBeens);
                            initAddImage();
                        }

                    }
                }
            });
            tileAdapter.setCanAddImages(MAX_IMAGES);

            tileAdapter.setStartOrEndLimit(true, 1);
        }else {
            tileAdapter.setRxSubscriber(null);
            tileAdapter.setCanAddImages(0);
            tileAdapter.setStartOrEndLimit(false, 9);
        }
    }

    //将选择的图片集合传进来 不是全部的图片
    private List<IDragEntity> obtainData() {
        paths.clear();
        List<IDragEntity> listEntity = new ArrayList<>();
        //有等于号的目的 是在最后加个添加图片的背景图
        //选择图片等于最大的数量时，不在添加增加图片的资源图
        chooseImages = mediaBeens.size();
        if (tileAdapter != null){
            tileAdapter.setImgNum(chooseImages, MAX_IMAGES);
        }

        int allCount = chooseImages >=MAX_IMAGES ? chooseImages-1 : chooseImages;

        for (int i = 0; i <= allCount; i++) {
            SimpleDragEntity entry = new SimpleDragEntity();
            if (i <chooseImages){
//                Log.d("jjf", mediaBeens.get(0).getOriginalPath());
                entry.setId(i);
                entry.setName("name " + i);
                String bigPath = mediaBeens.get(i).getThumbnailBigPath();
                if (!new File(bigPath).exists()){
                    bigPath = mediaBeens.get(i).getOriginalPath();
                }
                entry.setImageUrl(bigPath);
                paths.add(bigPath);
            }else {
                entry.setId(i);
                entry.setName("name " + i);
                entry.setResImage(R.drawable.fast_add_image);
            }
            listEntity.add(entry);
        }
        return listEntity;
    }

    @Override
    public DragDropListView getDragDropListView() {
        return mListView;
    }

    @Override
    public void onDataSetChangedForResult(ArrayList<IDragEntity> list) {
        // TODO you can save the result
        //重新排序后返回的结果
        //按照返回的顺序将原来mediaBeens里的数据排序 不然删除操作时，顺序会打乱
        ArrayList<MediaBean> listMedias = new ArrayList<>();
        Log.d("ttt", "++++++++"+list.size()+"========"+mediaBeens.size());
        for (IDragEntity e : list){
            for (MediaBean bean : mediaBeens){
                String url = ((SimpleDragEntity)e).getImageUrl();
                if (TextUtils.isEmpty(url))
                    continue;
                if (url.equals(bean.getThumbnailBigPath())){
                    listMedias.add(bean);
                    break;
                }
            }
        }
        mediaBeens.clear();
        mediaBeens = listMedias;
    }

    /**
     * 获取自己关注的社圈
     * */
//    private void getMyFollowCycles(){
//        CycleHttpUtils.getUtils().getFollowCircle(this, UCommonUtil.getUtil().getId(), 1, 999, 0, new OnHttpResultListener<CycleBean>() {
//            @Override
//            public void onResult(int status, String msg, int total, List<CycleBean> list) {
//                if (list != null){
//                    initTag(list);
//                }
//            }
//        });
//    }


    //压缩上传图片
    private void releaseImg(){
        if (paths != null && paths.size() >0){
            LoadingUtils.getUtils().loading(this);

            //如果上传是一张图片 获取图片宽高
            if (paths.size() ==1){
                int[] ints = ImageManagerUtils.getUtils().getImageWH(paths.get(0));
                imgsWidth = ints[0];
                imgsHeight = ints[1];
                Log.d("jjf", "宽="+ints[0]+"=高="+ints[1]);
            }

            ImageManagerUtils.getUtils().compressAndPost(this, OSSManager.OSS_CITY, paths, 500, false, new ImageManagerUtils.ImageCompressListener() {
                @Override
                public void onResult(int stutas, String cover, String result) {
                    if (stutas != 0){
                        isAllow = true;
                        LoadingUtils.getUtils().hide();
                        UCommonUtil.getUtil().showToast(ReleaseDynamicActivity.this, "上传失败");
                        return;
                    }

                    ossCover = cover;
                    ossResult = result;
                    release();

                }
            });
        }else {
            release();
        }
    }

    //发布按钮
    private void release(){
        MapRequest map = new MapRequest();
//        if (selectCycleBean != null){
//            map.put(BaseConfig.CYCLE_ID, selectCycleBean.getId());
//            map.put(BaseConfig.CYCLE_NAME, selectCycleBean.getCycleName());
//        }
        if (cycleId >0){
            map.put(BaseConfig.CYCLE_ID, cycleId);
            if (!TextUtils.isEmpty(cycleName)){
                map.put(BaseConfig.CYCLE_NAME, cycleName);
            }
        }
        map.put(BaseConfig.SHARE_CONTENT, editString);
        map.put(BaseConfig.SHARE_IMG, ossResult);
        map.put(BaseConfig.SHARE_COVER, ossCover);
        map.put(BaseConfig.SHARE_TYPE, BaseConfig.CYCLLE_DYNAMIC);
        map.put(BaseConfig.UNI_ID, UChengApplication.myUniId);
        map.put(BaseConfig.UNI_NAME, UChengApplication.mySchoolName);
        if (imgsWidth >0){
            map.put(BaseConfig.IMG_WIDTH, imgsWidth);
            map.put(BaseConfig.IMG_HEIGHT, imgsHeight);
        }



        CycleHttpUtils.getUtils().releaseCycleInfo(this, map, new OnResultListener() {
            @Override
            public void onResult(int stutas, String msg, int total, String data) {
                isAllow = true;
                if (stutas ==0){
                    UCommonUtil.getUtil().showToast(ReleaseDynamicActivity.this, "发布成功");
                    BaseConfig.isRelease = true;

//                    if (!BaseConfig.isReFresh){
//                        Intent intent = new Intent(ReleaseDynamicActivity.this, LoadCycleWebHtmlActivity.class);
//                        intent.putExtra(BaseConfig.PUB_TYPE, 1);
//                        intent.putExtra(BaseConfig.URL, BaseConfig.BaseWebURL+"/shares");
//                        startActivity(intent);
//                    }
                    BaseConfig.isReFresh = false;

                    ReleaseDynamicActivity.this.finish();
                }else {
                    UCommonUtil.getUtil().showToast(ReleaseDynamicActivity.this, "请重试");
                }
            }
        });
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.dynamic_add:
                //添加新的社圈
//                Intent intent = new Intent(this, LoadCycleWebHtmlActivity.class);
//                //true代表从发布界面进去的  点击返回按钮 会回调app的closeCurrentView关闭界面
//                intent.putExtra(BaseConfig.URL, BaseConfig.BaseWebURL + "/cycle/square");
//                intent.putExtra(BaseConfig.TYPE, 1);
//                startActivityForResult(intent, 0);
                break;
        }
    }

    @Override
    public void onBackPressed() {
        save();
    }

    /**
     * 获取之前保存的信息
     * */
    private CycleShareBean getSave(){
        List<CycleShareBean> shareBeanList = LiteOrmDBUtil.getLiteOrm(this).getQueryByWhere(CycleShareBean.class, "shareType", BaseConfig.CYCLLE_DYNAMIC);
        if (shareBeanList != null && shareBeanList.size() >0){
            LiteOrmDBUtil.getLiteOrm(this).deleteWhere(CycleShareBean.class, "shareType", BaseConfig.CYCLLE_DYNAMIC);
            return shareBeanList.get(0);
        }

        return null;
    }

    /**
     * 保存没有发布的信息
     * */
    private void save(){
        UCommonUtil.getUtil().hideSoftInput(this, dynamic_edit);
        editString = dynamic_edit.getText().toString();
        if (!TextUtils.isEmpty(editString) || (paths != null && paths.size() >0)){
            //有数据 保存
            CycleShareBean shareBean = new CycleShareBean();
            shareBean.setShareType(1);
            shareBean.setShareContent(dynamic_edit.getText().toString());
            if (paths != null && paths.size() >0){
                StringBuilder imgString = new StringBuilder();
                for (int i=0; i< paths.size(); i++){
                    String s = paths.get(i);
                    if (i ==0){
                        imgString.append(s);
                    }else {
                        imgString.append(";");
                        imgString.append(s);
                    }
                }
                String s = imgString.toString();
                shareBean.setShareImg(imgString.toString());
            }
            if (selectCycleBean != null){
                shareBean.setCycleId(selectCycleBean.getId());
            }

            LiteOrmDBUtil.getLiteOrm(this).insert(shareBean);
        }
        finish();
    }

//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        if (data != null && requestCode == 0){
//            getMyFollowCycles();
//        }
//    }
}
